// pages/device/index.js
const storageService = require('../../../services/storage')
import * as comm from '../../../utils/common'; //加载mqtt库
import {
  Toast
} from 'tdesign-miniprogram';


// 获取 App 实例
const appInstance = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    did: "",
    autoRunCfg: {},
    deviceCfg: {},
    deviceTime: "00:00",
    deviceTemp: 0,
    autoRun: 0,
    autoRunTitle: "",
    autoRunTmpVal: 0,

    selType: 0,
    syncCor: "#FFF",

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    this.setData({
      did: options.did
    });
    let autoRunCfg =  storageService.getAutoRunCfg(this.data.did)
    console.log(autoRunCfg);
    let title = autoRunCfg.tRun;
    if (comm.isEmpty(title) || title == "null") {
      title = "未同步";
    }
    let selType = autoRunCfg.selType == null ? 1 : autoRunCfg.selType;
    let autoRun = autoRunCfg.sRun == null ? 0 : autoRunCfg.sRun;
    let syncType = autoRunCfg.syncType == null ? 0 : autoRunCfg.syncType;
    let cor = this.getSelCor(syncType);
    this.setData({
      syncCor: cor,
      selType: selType,
      autoRun: autoRun,
      autoRunTitle: title
    });
    this.data.autoRunCfg = autoRunCfg;

    let dobj = storageService.getDeviceInfo(options.did)
    this.data.deviceCfg = dobj;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    const $t = this;
    wx.$event.on(this.data.deviceCfg.topicSub, this, (obj) => {
      if (obj.type == "status") {
        let syncType = (obj.msg.sT != null && obj.msg.sT != 0) ? obj.msg.sT : (obj.msg.tRun != '未同步' ? 1 : 0);
        let cor = $t.getSelCor(syncType);
        if (obj.msg.tRun != $t.data.autoRunTitle || obj.msg.sRun != $t.data.autoRun || cor != $t.data.syncCor) {
          $t.data.autoRunCfg.tRun = obj.msg.tRun;
          $t.data.autoRunCfg.sRun = obj.msg.sRun;
          $t.data.autoRunCfg.syncType = syncType;
        }
        $t.setData({
          syncCor: cor,
          autoRun: obj.msg.sRun,
          autoRunTitle: obj.msg.tRun,
          deviceTime: obj.msg.time,
          deviceTemp: obj.msg.tempNow
        });
      } else if (obj.type == "chgAutoRun") {
        $t.switchChangeResult(1);
      } else if (obj.type == "syncDataUp" || obj.type == "syncHandUp") {
        $t.handleSyncToDeviceDialogResult(1);
      } else if (obj.type == "syncDataDown") {
        $t.handleSyncFromDeviceDialogResult(1, JSON.parse(obj.msg));
      }
    });
    appInstance.sendMtMsg($t.data.deviceCfg.topicSend, "online", null);
  },
  onGoHome() {
    wx.redirectTo({
      url: "/pages/index/index",
    });
  },
  switchChange(e) {
    if (comm.isEmpty(this.data.autoRunTitle)) {
      $t.showToast("请先同步配置到设备!");
      return;
    }
    const $t = this;
    wx.showLoading({
      title: 'Loading......',
      mask: true,
      success: function () {
        $t.data.autoRunTmpVal = e.detail.value;
        appInstance.sendMtMsg($t.data.deviceCfg.topicSend, "chgAutoRun", e.detail.value ? 1 : 0);
        $t.data.timeoutObj = setTimeout(function () {
          $t.switchChangeResult(0);
        }, 5000);
      }
    });
  },
  switchChangeResult(succ) {
    const $t = this;
    wx.hideLoading();
    if (succ == 0) {
      $t.showToast("请求响应超时...");
    } else {
      $t.showToast("切换成功!");
      $t.setData({
        autoRun: $t.data.autoRunTmpVal ? 1 : 0
      });
      clearTimeout($t.data.timeoutObj);
      this.data.autoRunCfg.sRun = this.data.autoRun;
      storageService.saveAutoRunCfg(this.data.did, this.data.autoRunCfg)
    }
  },

  handleSyncToDeviceDialogResult(succ) {
    let child = null;
    if (this.data.selType == 1) {
      child = this.selectComponent('.childFree');
    } else if (this.data.selType == 2) {
      child = this.selectComponent('.childHand');
    } else if (this.data.selType == 3) {
      child = this.selectComponent('.childUpdown');
    }
    if (child != null) {
      child.confirmPopSyncToDeviceDialogResult(succ);
    }
  },
  handleSyncFromDeviceDialogResult(succ, dcfg) {
    const child = this.selectComponent('.childFree');
    child.confirmPopSyncFromDeviceDialogResult(succ, dcfg);
  },
  changeTab(e) {
    let type = e.target.dataset.type;
    if (type == this.data.selType) {
      return;
    }
    this.setData({
      selType: type
    });
    this.data.autoRunCfg.selType = type;
    storageService.saveAutoRunCfg(this.data.did, this.data.autoRunCfg)
  },
  cSetTitle(e) {
    let cor = this.getSelCor(e.detail.type);
    this.setData({
      syncCor: cor,
      autoRunTitle: e.detail.title
    });
    this.data.autoRunCfg.syncType = e.detail.type;
    this.data.autoRunCfg.tRun = e.detail.title;
    storageService.saveAutoRunCfg(this.data.did, this.data.autoRunCfg)
  },
  getSelCor(selType) {
    let cor = "#FFF";
    if (selType == 1) {
      cor = "#F56C6C";
    } else if (selType == 2) {
      cor = "#409EFF";
    } else if (selType == 3) {
      cor = "#E6A23C";
    }
    return cor;
  },
  jump2Set() {
    wx.navigateTo({
      url: '/packageC/pages/set/index?did=' + this.data.did,
      fail: function (res) {
        console.log(res);
      }
    });
  },






  showToast(msg) {
    Toast({
      context: this,
      selector: '#t-toast',
      message: msg,
    });
  },
  cShowToast(e) {
    this.showToast(e.detail.msg);
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.$event.remove(this.data.deviceCfg.topicSub, this);
  },
})